﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 委托
{
    class Program
    {
        public static int Multiply(int a, int b)
        {
            return a * b;
        }

        public static int Plus(int a, int b)
        {
            return a + b;
        }

        public static void Multiply2(int a, int b)
        {
            Console.WriteLine(a * b);
        }

        public static void Plus2(int a, int b)
        {
            Console.WriteLine(a + b);
        }


        static void Main(string[] args)
        {
            Func<int, int, int> func = Plus;

            Func<int, int, int> func1 = (a, b) => a * b;

            var lll = func1(2, 30);

            var kkk = func(1, 2);


            Action<int, int> action = Plus2;
            action += Multiply2;
            action(2, 3);


            MessageProducer messageProducer = new MessageProducer();
            Subscriber subscriber1 = new Subscriber("AAAA");
            Subscriber subscriber2 = new Subscriber("BBB");
            Subscriber subscriber3 = new Subscriber("CCC");
            messageProducer.Subscribe(subscriber1);
            messageProducer.Subscribe(subscriber2);
            messageProducer.Subscribe(subscriber3);
            messageProducer.Produce("发送1");
            messageProducer.Subscribe(subscriber2);
            messageProducer.Produce("发送2");
        }
    }
    public delegate void MessageProducerHandler(string message);

    public class Subscriber
    {
        public string Name { get; set; }

        public Subscriber(string name)
        {
            Name = name;
        }

        public void OnMessage(string messge)
        {
            Console.WriteLine($"{Name}收到消息{messge}");
        }
    }

    public class MessageProducer
    {
        public event MessageProducerHandler MessageHandle;

        public void Subscribe(Subscriber subscriber)
        {
            MessageHandle += subscriber.OnMessage;
        }


        public void UnSubscribe(Subscriber subscriber)
        {
            MessageHandle -= subscriber.OnMessage;
        }

        public void Produce(string message)
        {
            Console.WriteLine($"发布消息【{message}】");
            MessageHandle?.Invoke(message);
        }
    }
}
